package base

import "fmt"

// SortMap 用于排序的 map
type SortMap struct {
	sortKeys []string
	dataMap  map[string]interface{}
}

func NewSortMap() *SortMap {
	return &SortMap{
		sortKeys: make([]string, 0),
		dataMap:  make(map[string]interface{}),
	}
}

func (s *SortMap) Add(key string, value interface{}) *SortMap {
	if _, ok := s.dataMap[key]; !ok {
		s.sortKeys = append(s.sortKeys, key)
		s.dataMap[key] = value
	}
	return s
}

func (s *SortMap) Delete(key string) *SortMap {
	_, ok := s.dataMap[key]
	if !ok {
		return s
	}

	tmpIndex := -1
	for i, k := range s.sortKeys {
		if k == key {
			tmpIndex = i
			break
		}
	}
	if tmpIndex == -1 {
		return s
	}

	// 处理 sortKeys
	// 通过清空在append达到复用
	l := len(s.sortKeys)
	if tmpIndex == 0 {
		s.sortKeys = append(s.sortKeys[:0], s.sortKeys[1:]...)
	} else if tmpIndex == l-1 {
		s.sortKeys = append(s.sortKeys[:0], s.sortKeys[:l-1]...)
	} else {
		s.sortKeys = append(s.sortKeys[:tmpIndex], s.sortKeys[tmpIndex+1:]...)
	}

	// 处理 map
	delete(s.dataMap, key)
	return s
}

func (s *SortMap) Get(key string) (interface{}, bool) {
	value, ok := s.dataMap[key]
	return value, ok
}

func (s *SortMap) Range(f func(key string, value interface{}) error) error {
	for _, k := range s.sortKeys {
		if err := f(k, s.dataMap[k]); err != nil {
			return err
		}
	}
	return nil
}

func (s *SortMap) String() string {
	return fmt.Sprintf("%+v", s.dataMap)
}
